package com.example.zooker.curator.zookercurator;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;

public class LockDemo {
    private static CuratorFramework framework = null;


    public static void main(String[] args) throws IOException {
        framework = CuratorFrameworkFactory.builder()
                .connectString("localhost:2181")
                .sessionTimeoutMs(5000)
                .retryPolicy(new ExponentialBackoffRetry(1000, 3))
                .build();
        framework.start();
        System.out.println("启动");
        final InterProcessMutex lock = new InterProcessMutex(framework, "/locks");
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                try {
                    //获得锁
                    lock.acquire();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "->竞争锁");
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        System.out.println(Thread.currentThread().getName() + "->获得锁");
                        lock.release();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }, "Thread:" + i).start();


        }
        System.in.read();
    }


}
